<?php

namespace app\controller;

use support\bootstrap\Log;
use support\bootstrap\Redis;
use support\Request;

class Wb
{
    public const WB_AKEY = '77339523';
    public const WB_SKEY = 'c54fe6b17d200209c29b96312fec0b5f';
    public const WB_CALLBACK_URL = 'https://wb.liubao.org.cn/wb/callback';

    public function authorize()
    {
        $o = new \SaeTOAuthV2(Wb::WB_AKEY, Wb::WB_SKEY);
        $code_url = $o->getAuthorizeURL(Wb::WB_CALLBACK_URL);
        return redirect($code_url);
    }

    public function callback(Request $request)
    {
        try {
            $code = $request->get('code');
            $keys['code'] = $code;
            $keys['redirect_uri'] = Wb::WB_CALLBACK_URL;
            $o = new \SaeTOAuthV2(Wb::WB_AKEY, Wb::WB_SKEY);
            $token = $o->getAccessToken('code', $keys);
            Log::info('$keys|$token=', [$keys, '|', $token]);
            Redis::set('uid_' . $token['uid'], $token['access_token'], 'EX', $token['expires_in']);
            $wb_token = JWT::encode($token['access_token']);
            return json(['code' => 0, 'msg' => '授权成功', 'result' => ['wb_token' => $wb_token]]);
        } catch (\Exception $e) {
            Log::error('授权失败', [$e]);
            return json(['code' => 500, 'msg' => '授权失败']);
        }
    }

    public function revokeoauth2(Request $request)
    {
        return json(['code' => 0, 'msg' => '取消授权成功']);
    }

    public function publish(Request $request)
    {
        $content = $request->get('content', '测试发布信息');
        try {
            print_r($request->wb_token);
            $o = new \SaeTClientV2(Wb::WB_AKEY, Wb::WB_SKEY, $request->wb_token);
            $result = $o->update($content);
            print_r($result);
            return json(['code' => 0, 'msg' => '发布成功', 'result' => $result]);
        } catch (\Exception $e) {
            Log::error('发布异常', [$e]);
            return json(['code' => 500, 'msg' => '发布异常']);
        }
    }

    public function friends_timeline(Request $request)
    {
        $post = $request->rawBody();
        $page = (int)json_decode($post)->page || 1;
        $count = (int)json_decode($post)->limit || 50;
        $o = new \SaeTClientV2(Wb::WB_AKEY, Wb::WB_SKEY, $request->wb_token);
        $result = $o->friends_timeline($page, $count);
        return json(['code' => 0, 'msg' => '获取成功', 'result' => $result]);
    }


}
